package com.metis.document.parse.dialog.utils;

import com.metis.document.parse.dialog.models.dto.ParagraphTextElementDTO;
import com.metis.document.parse.dialog.models.dto.ParseResultDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDecimalNumber;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPPr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import static com.metis.document.parse.dialog.enums.ElementTypeEnum.PARAGRAPH;

/**
 * 这个是 word 提取 核心类
 */
@SuppressWarnings("unused")
public class WordExtractor {

    private final static Logger logger = LoggerFactory.getLogger(WordExtractor.class);

    public static WordExtractor instance = new WordExtractor();

    private WordExtractor(){}

    /**
     * parse doc
     *
     * @param fis fis
     * @return ParseResultDTO
     *
     * String path = "/Users/jxx/workspace/work-space/metis-document-parse-dialog/data/4_国家电网有限公司输变电工程标准工艺（架空线路分册）2022版(1).docx";
     * FileInputStream fis = new FileInputStream(path);
     * ByteArrayMultipartFile fis = new ByteArrayMultipartFile("","","");
     *
     * ----------------------------下边是测试用代码----------------------------
     *             // 遍历表格
     * //            for (XWPFTable table : document.getTables()) {
     * //                for (XWPFTableRow row : table.getRows()) {
     * //                    for (XWPFTableCell paragraph : row.getTableCells()) {
     * //                        System.out.println(paragraph.getText());
     * //                    }
     * //                }
     * //            }
     *
     * //            // 遍历图片注释
     * //            List<XWPFPictureData> pictures = document.getAllPictures();
     * //            for (XWPFPictureData picture : pictures) {
     * //                // 这里只是简单地打印了图片类型和图片数据，具体处理方式根据需要
     * //                System.out.println("图片类型: " + picture.getPictureType());
     * //                System.out.println("图片数据: " + Arrays.toString(picture.getData()));
     * //            }
     * ----------------------------测试用代码结束了----------------------------
     */
    public ParseResultDTO parseDoc(ByteArrayMultipartFile fis) {

        ParseResultDTO parseResultDTO = new ParseResultDTO();
        try (XWPFDocument document = new XWPFDocument(fis.getInputStream())) {
            Collection<ParagraphTextElementDTO> paragraphs = new ArrayList<>();

            // 遍历段落
            for (int i = 0; i < document.getParagraphs().size(); i++) {

                XWPFParagraph paragraph = document.getParagraphs().get(i);
                CTPPr pPr = paragraph.getCTP().getPPr();
                ParagraphTextElementDTO pd = new ParagraphTextElementDTO();
                pd.setParagraphId(i);
                pd.setType(PARAGRAPH);

                String text = paragraph.getText().trim();
                if (StringUtils.isEmpty(text)) {
                    continue;
                }

                pd.setText("");
                pd.setX((double) i);
                pd.setY(0.0);
                pd.getLineTexts().add(text);

                if (null != pPr) {
                    CTDecimalNumber outlineLvl = pPr.getOutlineLvl();
                    if (outlineLvl != null) {
                        int lev = outlineLvl.getVal().intValue();
                        pd.setLevel(lev);
                        pd.setText(text);
                    }
                }

                paragraphs.add(pd);
            }

            parseResultDTO.setParagraphs(paragraphs);
            logger.info(String.format("doc 提取结束: {%s}", fis.getOriginalFilename()));

            document.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return parseResultDTO;
    }

}
